package sync

import (
	"fmt"
	"strconv"
	"sync"
	"time"
)

func hello(wg *sync.WaitGroup) {
	defer wg.Done()
	time.Sleep(time.Second * 5)
	fmt.Println("Hello Goroutine!")
}
func wait() {
	var wg sync.WaitGroup
	wg.Add(1)
	go hello(&wg) // 启动另外一个goroutine去执行hello函数
	fmt.Println("main goroutine done!")
	wg.Wait() // 待协程执行结束
}

var m = make(map[string]int)

func get(key string) int {
	return m[key]
}

func set(key string, value int) {
	m[key] = value
}

func map_no_sync() {
	wg := &sync.WaitGroup{}
	for i := 0; i < 32; i++ {
		wg.Add(1)
		go func(n int, w *sync.WaitGroup) {
			key := strconv.Itoa(n)
			set(key, n)
			fmt.Printf("k=:%v,v:=%v\n", key, get(key))
			w.Done()
		}(i, wg)
	}
	wg.Wait()
}

func map_by_sync() {
	var rwlock sync.RWMutex

	for i := 0; i < 32; i++ {
		go func(n int) {
			rwlock.Lock()
			key := strconv.Itoa(n)
			set(key, n)
			fmt.Printf("k=:%v,v:=%v\n", key, get(key))
			rwlock.Unlock()
		}(i)
	}
}

var mp = sync.Map{}

func map_sync() {
	wg := sync.WaitGroup{}
	for i := 0; i < 20; i++ {
		wg.Add(1)
		go func(n int) {
			key := strconv.Itoa(n)
			mp.Store(key, n)
			value, _ := mp.Load(key)
			fmt.Printf("k=:%v,v:=%v\n", key, value)
			wg.Done()
		}(i)
	}
	wg.Wait()
}
